﻿using System;
using System.Collections.Specialized;
using System.Web;
using System.Xml;

namespace BitworkStudios.Web.Mvc.Framework.SiteMap.Providers
{
    public class XmlSiteMapProvider : SiteMapProviderBase
    {
        private const String SiteMapNodeName = "siteMapNode";
        private String _siteMapFileName;

        public XmlSiteMapProvider(string name, NameValueCollection attributes)
        {
            Initialize(name, attributes);
        }

        public override SiteMapNode BuildSiteMap()
        {
            lock (this)
            {
                if (null == _rootNode)
                {
                    Clear();
                    // Load the sitemap's xml from the file.
                    XmlDocument siteMapXml = LoadSiteMapXml();
                    // Create the first site map item from the top node in the xml.
                    var rootElement = (XmlElement)siteMapXml.GetElementsByTagName(SiteMapNodeName)[0];
                    // This is the key method - add the dynamic nodes to the xml
                    //AddDynamicNodes(rootElement);
                    // Now build up the site map structure from the xml
                    GenerateSiteMapNodes(rootElement);
                }
            }
            return _rootNode;
        }

        private XmlDocument LoadSiteMapXml()
        {
            var siteMapXml = new XmlDocument();
            siteMapXml.Load(AppDomain.CurrentDomain.BaseDirectory + _siteMapFileName);
            return siteMapXml;
        }

        protected override SiteMapNode GetRootNodeCore()
        {
            return RootNode;
        }

        protected override sealed void Initialize(string name, NameValueCollection attributes)
        {
            if (attributes != null)
                _siteMapFileName = attributes["siteMapFile"];
        }
    }
}
